package com.bo.rabbit.utils;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;

/**
 * @program rabbit
 * @Description
 * @Author Diviner
 * @Date 2024/03/26 12:24
 * @Version 1.0
 */
@Component
public class MinIOFileUtils {
    @Autowired
    MinioClient minioClient;

    /**
     * 创建桶
     * @param bucketFiles
     * @return
     */
    public boolean createBucket(String bucketFiles) {
        //
        String pub = "{\"Version\":\"2012-10-17\"," +
                "\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":" +
                "{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"," +
                "\"s3:GetBucketLocation\"],\"Resource\":[\"arn:aws:s3:::" + bucketFiles +
                "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:PutObject\",\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\"],\"Resource\":[\"arn:aws:s3:::" +
                bucketFiles +
                "/*\"]}]}";
        try {
            if (!bucketExist(bucketFiles)) {
                //创建桶
                minioClient.makeBucket(
                        MakeBucketArgs.builder().
                                bucket(bucketFiles).
                                build()
                );
                //设置桶的权限为public
                minioClient.setBucketPolicy(
                        SetBucketPolicyArgs.builder()
                                .bucket(bucketFiles)
                                .config(pub)
                                .build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 桶是否存在
     * @param bucketFiles
     * @return
     */
    public boolean bucketExist(String bucketFiles) {
        boolean exist=false;
        try {
            BucketExistsArgs bucket = BucketExistsArgs.builder().bucket(bucketFiles).build();
            exist = minioClient.bucketExists(bucket);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return exist;
    }

    /**
     * 上传文件
     * @param bucket
     * @param objectName
     */
    public void uploadFile(String bucket,String objectName,MultipartFile file){
        try {
            //创建临时文件夹
            File tempFile = File.createTempFile("minio", ".temp");
            file.transferTo(tempFile);
            String absolutePath = tempFile.getAbsolutePath();
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucket)//桶名称
                    .filename(absolutePath)//上传本地文件路径
                    .object(objectName)//上传命名称
                    .build();
            minioClient.uploadObject(uploadObjectArgs);
            //删除临时文件夹
            tempFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取按照年月日存储的文件名称
     * @param name
     * @return
     */
    public String fileName(String name){
        String fileName="";
        //获取年月日
        LocalDateTime currentTime = LocalDateTime.now();
        int year = currentTime.getYear();
        int month = currentTime.getMonthValue();
        int day = currentTime.getDayOfMonth();
        fileName=year+"/"+month+"/"+day+"/"+name;
        return fileName;
    }

    /**
     * 获取文件后缀名字
     * @param file
     * @return
     */
    public String getFileExtension(MultipartFile file){
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀名
        String fileExtension = null;
        if (originalFilename != null) {
            int lastIndex = originalFilename.lastIndexOf('.');
            if (lastIndex > 0) {
                fileExtension = originalFilename.substring(lastIndex + 1);
            }
        }
        return fileExtension;
    }
    public String getBucket(String fileExtension){
        String bucket="";
        if (fileExtension.equals("jpg")||fileExtension.equals("jpeg")||
                fileExtension.equals("png")||fileExtension.equals("gif")||
                fileExtension.equals("bmp")||fileExtension.equals("tiff")||
                fileExtension.equals("tif")||fileExtension.equals("webp")){
            bucket="picture";
        }else if (fileExtension.equals("mp4")||fileExtension.equals(".avi")||
                        fileExtension.equals("mkv")||fileExtension.equals("wmv")||
                        fileExtension.equals("mov")||fileExtension.equals("flv")||
                        fileExtension.equals("webm")){
            bucket="video";
        }else if(fileExtension.equals("pdf")||fileExtension.equals("doc")||
                fileExtension.equals("docx")||fileExtension.equals("xls")||
                fileExtension.equals("xlsx")||fileExtension.equals("ppt")||
                fileExtension.equals("pptx")||fileExtension.equals("txt")||
                fileExtension.equals("csv")||fileExtension.equals("rtf")||
                fileExtension.equals("html")){
            bucket="document";
        }else {
            bucket="other";
        }
        return bucket;
    }
}
